package com.topone.controller;

import com.topone.Converter.ConvenientInfoForm2ConvenientInfo;
import com.topone.Enum.ConvenientInfoEnum;
import com.topone.Exception.FanZoneException;
import com.topone.Form.ConvenientInfoForm;
import com.topone.Utils.KeyUntil;
import com.topone.Utils.ResultVOUntil;
import com.topone.VO.ResultVO;
import com.topone.dataObject.ConvenientInfo;
import com.topone.service.ConvenientInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * Created by Administrator on 2018/1/1,0001.
 */
@RestController
@CrossOrigin
@Slf4j
@RequestMapping("/buyer/convenientInfo")
public class BuyerConvenientInfoController {
    @Autowired
    private ConvenientInfoService service;

    @PostMapping(value = "/save")
    public ResultVO save(@RequestBody ConvenientInfoForm convenientInfoForm) {
        Map<String, Object> map = new HashMap<>();
        if (Objects.isNull(convenientInfoForm)) {
            return ResultVOUntil.error(1, "参数为空 convenientInfoForm=" + convenientInfoForm);
        }
        ConvenientInfo convenientInfo = ConvenientInfoForm2ConvenientInfo
                .convert(convenientInfoForm);
        log.debug("传入数据:{}", convenientInfo);

        //生成id
        convenientInfo.setConvenientId(KeyUntil.getUniqueKey());
        //提交订单 默认为待审核
        convenientInfo.setConvenientStatus(ConvenientInfoEnum.CHECK.getCode());
        try {
            service.save(convenientInfo);
        } catch (FanZoneException e) {
            log.error("【便民信息上传】申请保存失败!", e.getMessage());
            return ResultVOUntil.error(1, "【便民信息上传】申请保存失败!");
        }
        map.put("success", "提交成功");
        return ResultVOUntil.success(map);
    }

    @GetMapping("/list")
    public ResultVO<Map<String, Object>> convenientInfo() {
        Map<String, Object> map = new HashMap<>();
        try {
            List<ConvenientInfo> convenientInfoList = service
                    .findUpAll(ConvenientInfoEnum.ON.getCode());
            map.put("convenientInfoList", convenientInfoList);
        } catch (FanZoneException e) {
            log.error("【查询便民信息】e={}", e.getMessage());
            map.put("error", e.getMessage());
            return ResultVOUntil.error(1, e.getMessage());
        }
        log.info("【查询便民信息】成功,{}", map);
        map.put("success", "查询成功");
        return ResultVOUntil.success(map);
    }

}
